//
//  NiimbotModules.m
//  BOHRN
//
//  Created by Henry Chao on 2025/7/4.
//

#import "JCAPI.h"
#import "NiimbotModules.h"
#import <React/RCTLog.h>

@implementation NiimbotModules

// 必须导出模块。默认导出类名 NiimbotModules
RCT_EXPORT_MODULE();

// 返回支持的事件名
- (NSArray<NSString *> *)supportedEvents {
  return @[ @"NiimbotDiscoverPeripheral", @"NiimbotStopScan" ];
}

// 防止重复监听
+ (BOOL)requiresMainQueueSetup {
  return YES;
}

// 扫描
RCT_EXPORT_METHOD(startNiimbotScan : (NSDictionary *)params) {
  NSNumber *seconds = params[@"seconds"];
  if (!seconds) {
    seconds = @(3); // 默认 3 秒
  }
  // 调用蓝牙打印机扫描方法
  [JCAPI scanBluetoothPrinter:^(NSArray *scanedPrinterNames) {
    // 遍历扫描到的蓝牙打印机名字
    for (NSString *name in scanedPrinterNames) {
      // 检查名字长度，如果不在指定范围内，跳过
      if (name.length < 6 || name.length > 20) {
        continue;
      }
      [self sendEventWithName:@"NiimbotDiscoverPeripheral"
                         body:@{
                           @"id" : name,
                           @"name" : name,
                         }];
    }
  }];
  // 指定秒数后发送 StopScan
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)([seconds floatValue] * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [self sendEventWithName:@"NiimbotStopScan" body:nil];
  });
}

// 打印
RCT_EXPORT_METHOD(startNiimbotPrint : (NSDictionary *)params resolver : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject) {
  NSString *address = params[@"address"];
  NSString *labelsJson = params[@"labels"];
  NSString *paperType = params[@"paperType"];
  
  self.paperType = paperType;

  NSError *jsonError = nil;
  NSData *jsonData = [labelsJson dataUsingEncoding:NSUTF8StringEncoding];
  NSArray *labels = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&jsonError];

  if (jsonError || ![labels isKindOfClass:[NSArray class]]) {
    reject(@"INVALID_LABELS", @"标签 JSON 解析失败", jsonError);
    return;
  }

  // 防止重复回调
  __block BOOL callbackCalled = NO;
  // 连接打印机
  [JCAPI openPrinter:address
          completion:^(BOOL isSuccess) {
            if (isSuccess) {
              // 连接成功，打印
              [self printLabel:labels];
              if (!callbackCalled) {
                callbackCalled = YES;
                resolve(@{@"status" : @"success", @"message" : @"打印完成"});
              }
            } else {
              if (!callbackCalled) {
                callbackCalled = YES;
                reject(@"PRINT_FAILED", @"连接打印机失败", nil);
              }
            }
          }];
}

- (void)printLabel:(NSArray *)labels {
  //  [JCAPI initImageProcessing:arr.firstObject error:nil];
  [JCAPI setPrintWithCache:YES];
  
  NSInteger totalQuantity = 0;
  for (NSDictionary *label in labels) {
    NSNumber *printNum = label[@"printNum"] ?: @(1);
    totalQuantity += [printNum integerValue];
  }
  NSLog(@"totalQuantity:%ld", (long)totalQuantity);
  NSLog(@"测试-设置总打印份数");
  [JCAPI setTotalQuantityOfPrints:totalQuantity];
  
  // 循环绘制完成
  [JCAPI getPrintingErrorInfo:^(NSString *printInfo) {
    if ([printInfo isEqualToString:@"19"]) {
    } else {
      NSLog(@"---------printInfo=%@", printInfo);
      NSString *desc = nil;
      switch (printInfo.integerValue) {
      case 1:
        desc = @"异常:盒盖打开! 错误码1";
        break;
      case 33:
        desc = @"异常:不支持的材质! 错误码33";
        break;
      default:
        desc = [NSString stringWithFormat:@"未知错误，错误码:%@", printInfo];
        break;
      }
      NSLog(@"------------getPrintingErrorInfo:--%@", desc);
    }
  }];
  
  [JCAPI getPrintingCountInfo:^(NSDictionary *dic) {
    NSLog(@"------------获取的页码为:--%@", dic);

    NSString *totalCount = [dic valueForKey:@"totalCount"];
    NSLog(@"已打印份数为：%@", totalCount);
    NSLog(@"总打印份数为：%ld", (long)totalQuantity);
    if (totalCount.intValue == totalQuantity) {
      [JCAPI endPrint:^(BOOL isSuccess) {
        NSLog(@"------------getPrintingCountInfo:--打印完成");
        [JCAPI closePrinter];
      }];
    }
  }];
  
  NSLog(@"测试-开启打印任务");
  [JCAPI startJob:3
      withPaperStyle:1
      withCompletion:^(BOOL isSuccess) {
        NSLog(@"测试-开始生成打印数据并提交");
        NSLog(@"pageCount ：%ld", (long)1);
        [self generateLabelAndCommit:1 withTotalPages:totalQuantity withPrintedPages:0 withLabels:labels];
      }];
}

- (void)generateLabelAndCommit:(NSInteger)quantity withTotalPages:(NSInteger)totalPages withPrintedPages:(NSInteger)printedPages withLabels:(NSArray *)labels {
  // 计算页码
  NSInteger labelIndex = 0;
  NSInteger pageCount = 0;
  for (NSInteger i = 0; i < labels.count; i++) {
    NSDictionary *label = labels[i];
    NSInteger printNum = [label[@"printNum"] integerValue];
    if (printedPages < pageCount + printNum) {
      labelIndex = i;
      break;
    }
    pageCount += printNum;
  }
  NSDictionary *currentLabel = labels[labelIndex];
  // 绘制
  [self drawLabel:currentLabel];
  // 提交
  [self commitLabelGeneration:quantity withTotalPages:totalPages withPrintedPages:printedPages withLabels:labels];
}

- (void)drawLabel:(NSDictionary *)label {

  float width = 40;
  float height = 30;
  NSInteger orientation = 0;
  float fontSize = 3.0;

  if ([self.paperType isEqualToString:@"30x40"]) {
    orientation = 90;
  } else if ([self.paperType isEqualToString:@"40x40"]) {
    height = 40;
  } else if ([self.paperType isEqualToString:@"40x60"]) {
    height = 60;
  }

  [JCAPI initDrawingBoard:width withHeight:height withHorizontalShift:0 withVerticalShift:0 rotate:orientation fontArray:@[]];

  NSString *tagName = label[@"tagName"] ?: @"";
  NSString *vdmName = label[@"vdmName"] ?: @"";
  NSArray *formatList = label[@"vdmTagsConfigFormatList"];

  float y = 2.0;
  float space = 5.0;

  // 30x40或者40x30的标签，如果要打印超过4行，减少行间距
  if (self.paperType == nil || self.paperType.length == 0 || [self.paperType isEqualToString:@"30x40"]) {
    if (formatList != nil && formatList.count >= 4) {
      space = 4.0;
    }
  }

  [JCAPI DrawLableGraph:2 withY:2 withWidth:9 withHeight:9 withLineWidth:0.25 withCornerRadius:2 withRotate:0 withGraphType:3 withLineType:1 withDashWidth:@[ @0.7575, @0.7575 ]];

  // 打印 tagName（如“转容冷藏”）
  [JCAPI drawLableText:2 withY:y withWidth:9 withHeight:9 withString:tagName withFontFamily:@"" withFontSize:fontSize withRotate:0 withTextAlignHorizonral:1 withTextAlignVertical:1 withLineMode:4 withLetterSpacing:0 withLineSpacing:0 withFontStyle:@[ @0, @0, @0, @0 ]];

  // 打印 vdmName（如“椰子脆片”）
  [JCAPI drawLableText:13 withY:y withWidth:25 withHeight:9 withString:vdmName withFontFamily:@"" withFontSize:fontSize withRotate:0 withTextAlignHorizonral:0 withTextAlignVertical:1 withLineMode:4 withLetterSpacing:0 withLineSpacing:0 withFontStyle:@[ @0, @0, @0, @0 ]];
  y += 10;

  // 打印每一项 vdmTagsConfigFormatList
  for (NSString *line in formatList) {
    [JCAPI drawLableText:2 withY:y withWidth:36 withHeight:5 withString:line withFontFamily:@"" withFontSize:fontSize withRotate:0 withTextAlignHorizonral:0 withTextAlignVertical:1 withLineMode:4 withLetterSpacing:0 withLineSpacing:0 withFontStyle:@[ @0, @0, @0, @0 ]];
    y += space;
  }
}

- (void)commitLabelGeneration:(NSInteger)quantity withTotalPages:(NSInteger)totalPages withPrintedPages:(NSInteger)printedPages withLabels:(NSArray *)labels {
  NSLog(@"测试-提交数据总页数：%ld", (long)totalPages);
  NSLog(@"测试-提交数据已打印页数：%ld", (long)printedPages);

  NSString *data = [JCAPI GenerateLableJson];
  NSLog(@"打印数据：%@", data);
  [JCAPI commit:[JCAPI GenerateLableJson]
      withOnePageNumbers:(int)quantity
            withComplete:^(BOOL isSuccess) {
              // 此次还需要判断是否已经提交完成
              if (isSuccess) {
                NSLog(@"测试-提交数据总页数：%ld", (long)totalPages);
                if (totalPages > printedPages + 1) {
                  [self generateLabelAndCommit:quantity withTotalPages:totalPages withPrintedPages:printedPages + 1 withLabels:labels];
                } else {
                  NSLog(@"测试-数据已提交完成");
                }
              } else {
                NSLog(@"测试-数据提交失败");
              }
            }];
}

@end
